<?php

namespace SisesporteAdmin\Controller;

use Zend\View\Model\ViewModel;
use Sisesporte\Constant\TipoSituacaoTurmaConstant;

class SorteioController extends CrudController {

    public function indexAction() {
        $data = $this->getEm()
                        ->getRepository("Sisesporte\Entity\Turma")->findBy(array('sqSituacaoTurma' => TipoSituacaoTurmaConstant::A_SER_SORTEADA), array('dtSorteio' => 'ASC'));
        return new ViewModel(array('data' => $data));
    }

    public function newAction() {
        $data = $this->getEm()
                        ->getRepository("Sisesporte\Entity\Turma")->findBy(array('sqTurma' => $this->params()->fromRoute('id', 0)), array('dtSorteio' => 'ASC'));

        $preMatriculas = $this->getEm()
                        ->getRepository("Sisesporte\Entity\PreMatricula")->findBy(array('sqTurma' => $this->params()->fromRoute('id', 0)), array('sqPreMatricula' => 'ASC'));

        $preSorteadas = NULL;
        if ($data[0]->getSqSituacaoTurma()->getSqSituacaoTurma() == TipoSituacaoTurmaConstant::SORTEADA ) {
            $preSorteadas = $this->getEm()
                            ->getRepository("Sisesporte\Entity\PreMatricula")->findBy(array('sqTurma' => $this->params()->fromRoute('id', 0)), array('nuOrdem' => 'ASC'));
        }

        return new ViewModel(array('data' => $data, 'preMatriculas' => $preMatriculas, 'preSorteadas' => $preSorteadas));
    }

    public function sortearAction() {
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();

            $serviceTurma = $this->getServiceLocator()->get("Sisesporte\Service\TurmaService");
            if ($serviceTurma->updateSituacaoSorteada($post['sqTurma'])) {
                $servicePreMatricula = $this->getServiceLocator()->get("Sisesporte\Service\PreMatriculaService");
                if ($servicePreMatricula->sorteados($post)) {
                    $data = "Sorteado com Sucesso";
                }
            }
        }

        $viewModel = new ViewModel(array('data' => $data));
        return $viewModel->setTerminal(TRUE);
    }

}
